<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload, Download, UploadFilled, Delete, CircleCheck, CircleClose, Warning } from '@element-plus/icons-vue'
import { spotAPI } from '@/api/index.js'
const summary = ref({
  totalCount: 0,
  successCount: 0,
  failedCount: 0,
  skippedCount: 0,
})
const uploadedFile = ref(null)
const importUploadRef = ref()
const importLoading = ref(false)
const progressData = ref([])
const showProgress = ref(false)
const progressTotal = ref(0)
const progressCurrent = ref(0)
const sortedProgressData = ref([])
const currentSortType = ref('default')

// 监听progressData变化，自动应用当前排序
watch(
  progressData,
  () => {
    applySorting(currentSortType.value)
  },
  { deep: true }
)

// 文件选择处理
const handleFileChange = (file) => {
  // 验证文件格式和大小
  const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']

  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('请上传Excel文件（.xlsx 或 .xls 格式）')
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
    return false
  }

  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB')
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
    return false
  }

  uploadedFile.value = file.raw
}

// 文件移除处理
const handleFileRemove = () => {
  uploadedFile.value = null
  console.log('File removed')
}

// 下载导入模板
const downloadTemplate = async () => {
  try {
    const response = await spotAPI.downloadTemplate()

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '点位导入模板.xlsx'
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('模板下载失败')
    }
  } catch (error) {
    ElMessage.error('模板下载失败')
    console.error('模板下载错误:', error)
  }
}

let timer = null

const getImportData = async (batchId) => {
  try {
    const { data } = await spotAPI.getImportProgress(batchId)
    progressData.value = data.records || []
    summary.value = data.summary || {
      totalCount: 0,
      successCount: 0,
      failedCount: 0,
    }
    if (data.completed) {
      clearInterval(timer)
      timer = null
      importLoading.value = false
      ElMessage.success('批量导入成功')
      uploadedFile.value = null
      if (importUploadRef.value) {
        importUploadRef.value.clearFiles()
      }
      return
    }
  } catch (error) {
    ElMessage.error('获取导入进度失败')
    clearInterval(timer)
    timer = null
  }
}

// 提交导入
const handleImportSubmit = async () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }
  importLoading.value = true
  showProgress.value = true
  spotAPI.import(uploadedFile.value).catch(() => {
    ElMessage.error(response.message || '导入失败')
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
    importLoading.value = false
    clearInterval(timer)
    timer = null
  })
  setTimeout(() => {
    getImportData()
  }, 1000)
  // 2. 轮询查看进度
  timer = setInterval(() => getImportData(), 2000)
}

// 清空进度数据
const clearProgress = () => {
  progressData.value = []
  sortedProgressData.value = []
  currentSortType.value = 'default'
  showProgress.value = false
  progressTotal.value = 0
  progressCurrent.value = 0
}

// 停止导入
const handleStopImport = () => {
  spotAPI
    .stopImport()
    .then(() => {
      ElMessage.success('已停止当前导入，可以重新上传文件进行导入')
      importLoading.value = false
      uploadedFile.value = null
      if (importUploadRef.value) {
        importUploadRef.value.clearFiles()
      }
      clearInterval(timer)
      timer = null
    })
    .catch(() => {
      ElMessage.error('停止导入失败，请稍后再试')
    })
}

// 应用排序
const applySorting = (sortType = 'default') => {
  currentSortType.value = sortType
  if (sortType === 'success-first') {
    sortedProgressData.value = [...progressData.value].sort((a, b) => {
      const aHasError = !!a.errorMessage
      const bHasError = !!b.errorMessage

      if (!aHasError && bHasError) return -1 // 成功的排在前面
      if (aHasError && !bHasError) return 1 // 失败的排在后面
      return 0
    })
  } else if (sortType === 'error-first') {
    sortedProgressData.value = [...progressData.value].sort((a, b) => {
      const aHasError = !!a.errorMessage
      const bHasError = !!b.errorMessage

      if (aHasError && !bHasError) return -1 // 失败的排在前面
      if (!aHasError && bHasError) return 1 // 成功的排在后面
      return 0
    })
  } else {
    sortedProgressData.value = [...progressData.value] // 默认顺序
  }
}

onMounted(() => {
  spotAPI
    .getImportProgress()
    .then((res) => {
      progressData.value = res.data.records || []
      summary.value = res.data.summary || {
        totalCount: 0,
        successCount: 0,
        failedCount: 0,
      }
      if (progressData.value.length > 0) {
        showProgress.value = true
        importLoading.value = true
        timer = setInterval(() => getImportData(), 2000)
      }
      if (res.data.completed) {
        importLoading.value = false
        clearInterval(timer)
        timer = null
      }
    })
    .catch(() => {
      ElMessage.error('获取导入进度失败')
    })
})
</script>

<template>
  <div class="import-container">
    <!-- 操作区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-content">
        <!-- 下载模板按钮 -->
        <div class="template-section">
          <el-button type="primary" @click="downloadTemplate" :icon="Download"> 下载导入模板 </el-button>
          <span class="template-tip">请先下载模板，按照格式填写数据后再上传</span>
        </div>

        <el-divider></el-divider>

        <!-- 文件上传区域 -->
        <div class="upload-section">
          <el-upload
            ref="importUploadRef"
            class="upload-demo"
            drag
            accept=".xlsx,.xls"
            :limit="1"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :auto-upload="false"
            :show-file-list="true"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将Excel文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
              <div class="el-upload__tip">只能上传.xlsx/.xls文件，且不超过10MB</div>
            </template>
          </el-upload>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button
            type="primary"
            :loading="importLoading"
            :disabled="!uploadedFile || importLoading"
            @click="handleImportSubmit"
            :icon="UploadFilled"
          >
            {{ importLoading ? '导入中...' : '开始导入' }}
          </el-button>

          <el-button v-if="showProgress" @click="handleStopImport" :icon="Upload"> 停止导入 </el-button>

          <el-button v-if="showProgress && !importLoading" @click="clearProgress" :icon="Delete"> 清空记录 </el-button>
        </div>
      </div>
    </el-card>

    <!-- 导入进度区域 -->
    <el-card v-if="showProgress" class="progress-card" shadow="never">
      <!-- 排序控制区域 -->
      <div class="sort-controls">
        <span class="sort-label">排序方式：</span>
        <el-button-group>
          <el-button
            size="small"
            :type="currentSortType === 'default' ? 'primary' : ''"
            @click="applySorting('default')"
          >
            默认
          </el-button>
          <el-button
            size="small"
            :type="currentSortType === 'success-first' ? 'success' : ''"
            @click="applySorting('success-first')"
          >
            成功优先
          </el-button>
          <el-button
            size="small"
            :type="currentSortType === 'error-first' ? 'danger' : ''"
            @click="applySorting('error-first')"
          >
            失败优先
          </el-button>
        </el-button-group>
      </div>

      <!-- 进度详情表格 -->
      <div class="progress-table-section">
        <el-table :data="sortedProgressData" border stripe max-height="800" style="width: 100%">
          <el-table-column prop="rowIndex" label="行号" width="80" align="center" />
          <el-table-column prop="spotName" label="点位名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="categoryName" label="分类名称" min-width="120" show-overflow-tooltip />
          <el-table-column prop="errorMessage" label="信息" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="scope.row.errorMessage" style="color: #f56c6c">
                {{ scope.row.errorMessage }}
              </span>
              <span v-else style="color: #67c23a">导入成功</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="处理时间" width="160" align="center" />
        </el-table>
      </div>

      <!-- 统计信息 -->
      <div class="statistics-section">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="总计" :value="summary.totalCount" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="成功" :value="summary.successCount" value-style="color: #67c23a" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="失败" :value="summary.failedCount" value-style="color: #f56c6c" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="跳过" :value="summary.skippedCount" value-style="color: #f56c6c" />
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.import-container {
  padding: 20px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  height: 100%;
  overflow-y: auto;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin-bottom: 20px;
  font-weight: 600;
}

.instruction-card,
.operation-card,
.progress-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.instruction-content {
  padding: 20px 0;
}

.operation-content {
  padding: 20px 0;
}

.template-section {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.template-tip {
  color: #909399;
  font-size: 14px;
}

.upload-section {
  margin-bottom: 30px;
}

.upload-demo {
  width: 100%;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.progress-summary {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-bar-section {
  margin-bottom: 20px;
}

.progress-table-section {
  margin-bottom: 20px;
}

.sort-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.sort-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.status-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.statistics-section {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

// Element Plus Upload 组件样式调整
:deep(.el-upload-dragger) {
  width: 100%;
  height: 180px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background-color: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;

  &:hover {
    border-color: #409eff;
    background-color: #f0f9ff;
  }
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  color: #606266;
  font-size: 16px;

  em {
    color: #409eff;
    font-style: normal;
    font-weight: 500;
  }
}

:deep(.el-upload__tip) {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
}

// 表格样式调整
:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f8f9fa;
      color: #333;
      font-weight: 600;
    }
  }
}

// 步骤条样式调整
:deep(.el-steps) {
  .el-step__title {
    font-size: 14px;
    font-weight: 500;
  }

  .el-step__description {
    font-size: 12px;
    color: #909399;
  }
}

// 统计数字样式
:deep(.el-statistic) {
  text-align: center;

  .el-statistic__head {
    font-size: 14px;
    color: #909399;
    margin-bottom: 8px;
  }

  .el-statistic__content {
    font-size: 24px;
    font-weight: 600;
  }
}
</style>
